//
//  HMRefreshControl.swift
//  新浪微博
//
//  Created by 饶鹏伟 on 16/4/14.
//  Copyright © 2016年 饶鹏伟. All rights reserved.
//

import UIKit

//控件的三种状态
enum HMRefreshStatue: Int {
    case Normal = 0    // 普通状态
    case Pulling = 1    //准备刷新状态
    case Refreshing = 2 //刷新状态
}

//刷新控件的高度
private let RefreshViewHight: CGFloat=60

//自定义下拉刷新控件
class HMRefreshControl: UIControl {
    
    //更具刷新控件的状态 来更新UI
    var statu: HMRefreshStatue = .Normal {
        
        //didSet 中 可以获取 newValue 和 oldValue
        didSet{
            //判断控件状态
            switch statu{
                
            case .Normal:
              
                tipLabel.text="下拉起飞"
             //停止转动小菊花和显示箭头
                indicatorView.stopAnimating()
                arrowicon.hidden = false
             //上一次的状态是 刷新状态  再减
                if oldValue == .Refreshing {
                    UIView.animateWithDuration(0.25, animations: { () -> Void in
                        var inset = self.scrollView!.contentInset
                        inset.top = inset.top - RefreshViewHight
                        self.scrollView?.contentInset = inset
                    })
                }
                
                //恢复箭头方向
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrowicon.transform = CGAffineTransformIdentity
                })
                
            case .Pulling:
            
                tipLabel.text="马上起飞"
                //旋转箭头
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrowicon.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
                
            case .Refreshing:
                
                tipLabel.text="正在起飞"
                //转动小菊花
                indicatorView.startAnimating()
                //隐藏箭头
                arrowicon.hidden = true
                //刷新数据 等待数据刷新成功之后  将状态改为 普通状态
                //主动给当前控件发送对应的事件类型 会自动找到对应的target 调用监听的方法
                sendActionsForControlEvents(.ValueChanged)
                
                //修改contentInset.top
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    var inset = self.scrollView!.contentInset
                    inset.top = inset.top + RefreshViewHight
                    self.scrollView?.contentInset = inset
                })
                
            }
            
        
        }
     
    }
    
    
    
    //视图将要移动到父视图上的时候会自动调用

     private var scrollView: UIScrollView?
    
    override func willMoveToSuperview(newSuperview: UIView?) {
        
        super.willMoveToSuperview(newSuperview)
        
        //print(newSuperview )
        //获取父视图
        if let myFather = newSuperview as? UIScrollView {
            //当前的刷新控件支持在滚动视图上添加
            //实时的获取滚动视图垂直方向的位移
            /*
            Observer: 要添加的观察着
            forKeyPath: 要观察的键值属性
            //KVO作用:观察对象的属性变化
            */
            
            self.scrollView = myFather
            myFather.addObserver(self, forKeyPath: "contentOffset", options: [.New], context: nil)
        
        }
    }
    
        //移除对象的属性观察
        deinit {
            scrollView?.removeObserver(self, forKeyPath: "contentOffset")
        }

    
    //添加观察者 监听属性的变化 要实现这个方法 当属性的值改变就会调用这个方法
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        //实时获取父视图的垂直方向位移   修改视图的状态
        
        let offsetY=scrollView?.contentOffset.y
        //print(offsetY)
        //需要对比的值 contentInset等于64
        let targetOffsetY = -scrollView!.contentInset.top - RefreshViewHight
        
        if scrollView!.dragging{//正在拖拽
            
            if statu == .Pulling && offsetY>targetOffsetY{
                
                //只要满足 位移 大于 -124 并且 当前状态是 准备刷新刷新状态
                print("普通状态")
                statu = .Normal
                
            }else if statu == .Normal && offsetY < targetOffsetY {
                
                print("准备刷新状态")
                statu = .Pulling
            }
        }else{//没有拖拽
            
            
            //没有拽动tableView && 当前状态是 准备刷新状态 才修改为 正在刷新状态
            if statu == .Pulling {
                print("正在刷新")
                statu = .Refreshing
                //转动小菊花
                indicatorView.startAnimating()
                //隐藏箭头
                arrowicon.hidden = true
            }
        }
        
    }
    
    
    
   
    //停止Refresh的转动
    func endRefreshing(){
        
        let delta=dispatch_time(DISPATCH_TIME_NOW, Int64(Double(NSEC_PER_SEC) * 0.9))
        
       dispatch_after(delta, dispatch_get_main_queue()) { () -> Void in
        
        self.statu = .Normal
        
        }
    }
    
    
    
    
    override init(frame: CGRect) {
        
        //指定默认大小
        let rect = CGRect(x: 0, y: -RefreshViewHight, width: ScreenWidth, height: RefreshViewHight)
        
        super.init(frame: rect)
        
        //设置界面
        setupUI()
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    //设置UI界面
    private func setupUI(){
        
      backgroundColor=UIColor.yellowColor()
        
        //添加子控件
        addSubview(arrowicon)
        addSubview(tipLabel)
        addSubview(indicatorView)
        
        //设置约束
        arrowicon.snp_makeConstraints { (make) -> Void in
            
            make.centerX.equalTo(self.snp_centerX).offset(-30)
            
            make.centerY.equalTo(self.snp_centerY)
            
        }
        
        tipLabel.snp_makeConstraints { (make) -> Void in
            
            make.left.equalTo(arrowicon.snp_right)
            
            make.centerY.equalTo(self.snp_centerY)
            
        }
        
        indicatorView.snp_makeConstraints { (make) -> Void in
            
            make.center.equalTo(arrowicon.snp_center)
            
        }
    }
    
    
    
  //懒加载子视图
    //箭头
    private lazy var arrowicon: UIImageView=UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    
    // 文字状态
    private lazy var tipLabel: UILabel=UILabel(text: "准备起飞", textColor: UIColor.darkGrayColor(), fontSize: 14)
    
    //菊花
    private lazy var indicatorView: UIActivityIndicatorView=UIActivityIndicatorView(activityIndicatorStyle: .Gray)

}
